<template>
  <div class="menu-component">
    <ul class="main-menu">
      <template v-for="item in menuData">
        <li v-if="item.url==='#'" class="main-menu-item" :class="{active:item.id===parentId}">
          <h2 @click="onMenu(item.id)">{{item.name}}</h2>
          <ul class="inner-menu" v-if="item.children" v-show="item.id===parentId">
            <router-link tag="li" :to="innerItem.url" class="inner-menu-item" :class="{active: active===innerItem.url}" v-for="innerItem in item.children" key="innerItem.name">{{innerItem.name}}
            </router-link>
          </ul>
        </li>
        <router-link v-else tag="li" :to="item.url" :key="item.name" class="main-menu-item" :class="{active:item.id===parentId}">
          <h2 @click="onMenu(item.id)">{{item.name}}</h2>
        </router-link>
      </template>
    </ul>
  </div>
</template>
<script type="text/javascript">
export default {
  props: {
    menuData: Array
  },
  data() {
    return {
      active: '',
      parentId: ''
    }
  },
  computed: {
    activeUrl() {
      let url = ''
      this.menuData.forEach(item => {
        if (item.children) {
          item.children.forEach(innerItem => {
            if (innerItem.url === this.active) {
              url = item.url
            }
          })
        }
      })
      return url
    }
  },
  mounted() {
    this.active = this.$route.path
    this.$router.afterEach((to) => {
      let path = to.path
      this.active = path
      if (path === '/index/welcome') {
        this.parentId = ''
      }
    })
    this.menuData.forEach(item => {
      if (item.children.length) {
        item.children.forEach(innerItem => {
          if (innerItem.url === this.active) {
            this.parentId = item.id
          }
        })
      } else {
        if (item.url === this.active) {
          this.parentId = item.id
        }
      }
    })
  },
  methods: {
    onMenu(id) {
      this.parentId = id
    }
  }
}

</script>
<style type="text/css" scoped>
.main-menu-item {
  width: 190px;
  line-height: 50px;
  text-indent: 36px;
  background-color: #fff;
  cursor: pointer;
}

.main-menu-item.active {
  background-color: #01378c;
}

.main-menu-item h2 {
  margin: 0;
  font-weight: 400;
  font-size: 18px;
  color: #282828;
}

.main-menu-item.active h2 {
  color: #fff;
}

.inner-menu-item {
  width: 190px;
  line-height: 50px;
  text-indent: 43px;
  background-color: #f5f9ff;
  font-size: 14px;
  cursor: pointer;
}

.inner-menu-item.active {
  color: #01378c;
}

</style>
